/*
 * Copyright 2012 Alain Pannetrat (L1L1@gmx.com)
 * 
 * This file is part of cookie-miner.
 * 
 * cookie-miner is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * cookie-miner is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with cookie-miner. If not, see http://www.gnu.org/licenses/.
 *
 * @version: $Id$
 *
 */
#include "keyvalue.h"
#include <cstdio>  // for sprintf
#include <cstdlib> // for atoi

std::string KeyValueList::dummy = "";

KeyValueList::iterator KeyValueList::find(const std::string& key, unsigned index)
{
	KeyValueList::iterator it;
	unsigned pos=0;

	for (it=begin();it!=end();++it)	
	{
		if (key==it->first) 
		{
			if (pos==index)	return it;
			pos++;
		}
	}
	return end();
}
		
KeyValueList::const_iterator KeyValueList::find(const std::string& key, unsigned index) const
{
	KeyValueList::const_iterator it;
	unsigned pos=0;

	for (it=begin();it!=end();++it)	
	{
		if (key==it->first) 
		{
			if (pos==index)	return it;
			pos++;
		}
	}
	return end();
}

bool KeyValueList::set(const std::string& field, const std::string& value, unsigned index)
{
	KeyValueList::iterator it = find(field,index);
	if (it!=end()) 
	{
		it->second=value;
		return true;
	}
	push_back(KeyValue(field,value));
	return true;
}
                
bool KeyValueList::set(const std::string& field, int value, unsigned index)
{
	char str_value[16];

	sprintf(str_value,"%i",value);
	return set(field,str_value,index);
}

const std::string& KeyValueList::get(const std::string& field, unsigned index) const
{
	KeyValueList::const_iterator it = find(field,index);
	if (it!=end()) return it->second;
	return dummy;
}

int KeyValueList::get_as_int(const std::string& field, unsigned index) const
{
	KeyValueList::const_iterator it = find(field,index);
	if (it!=end()) return atoi(it->second.c_str());
	return 0;
}

unsigned KeyValueList::exists(const std::string& key) const
{
	KeyValueList::const_iterator it;
	unsigned count=0;

	for (it=begin();it!=end();++it)	
	{
		if (key==it->first) count++;
	}
	return count;
}

KeyValueList::iterator KeyValueList::erase(KeyValueList::iterator it)
{
	if (it!=end()) 
		return std::list< std::pair<std::string,std::string> >::erase(it);
	return end();
}
/*
int main()
{
	KeyValueList kvl;
	KeyValueList::iterator it = kvl.begin();

	kvl.erase("a");
}*/
